package com.lizhaoshan.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: reggie
 * @description:
 * @author: lamour
 * @create: 2022-05-15 18:54
 **/
@Slf4j
@Service
public class TokenUtil {

    /**
     * 过期时间
     */
    private static final long EXPIRE_TIME = 45 * 60 * 1000;

    /**
     * token秘钥
     */
    private static final String TOKEN_SECRET = "c369a1e4-43ee-4e1e";

    /**
     * 根据用户名和密码，使用加密算法生成JWT的token令牌。
     * @param
     * @return
     */
    public static String createToken(String username,String id) {

        try {
            log.info("**********生成令牌");
            String token = "";
            /**
             * 这里用的是com.auth0.jwt的JWT，而不是cn.hutool.jwt的JWT
             */

            Map<String, Object> headers = new HashMap<>(2);
            //Header 头部(标题包含了令牌的元数据，并且包含签名和/或加密算法的类型)
            headers.put("type", "JWT");
            headers.put("algo", "HS256");

            // 过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            // 秘钥和加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);

            token = com.auth0.jwt.JWT.create()
                    .withHeader(headers)
                    .withClaim("username", username)
                    .withClaim("id", id)
                    .withExpiresAt(date)
                    .sign(algorithm);

            return token;
        } catch (IllegalArgumentException | JWTCreationException e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }


    /**
     * token 校验方法
     * @Param userName  userName
     * @return String role
     */
    public static boolean verify(String token) throws UnsupportedEncodingException {

        try {
            log.info("**********校验token begin.");

            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);

            log.info("**********校验token end.");
            return true;
        } catch (IllegalArgumentException | JWTVerificationException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取token中的username
     * @param token
     * @return
     */
    public static String getName(String token) {
        try {
            return JWT.decode(token).getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获取token中的password
     * @param token
     * @return
     */
    public static String getId(String token) {
        try {
            return JWT.decode(token).getClaim("id").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

}
